<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <title>单个手指的操作</title>
    <style type="text/css">
        html,
        body {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0
        }
        
        #canvas {
            position: relative;
            width: 100%;
            height: 100%;
        }
        
        .spirit {
            /* 方块的class名称*/
            position: absolute;
            width: 50px;
            height: 50px;
            background-color: red;
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <div id="canvas"></div>

    <script>
        // define global variable
        var canvase = document.getElementById("canvas"),
            spirit, startX, startY

        function touchStart(event) {
            // 防止手指的操作引起界面的滑动
            event.preventDefault();
            //容错处理，如果有了色块
            if (spirit || !event.touches.length) return;
            // 创建一个色块
            spirit = document.createElement('div')
            spirit.className = "spirit"
                // 计算出来当前点击的xy
            var touch = event.touches[0]
            startX = touch.clientX
            startY = touch.clientY
            console.log(`当前点击的坐标:X:${startX-25},Y:${startY-25}`)

            // 赋值给这个色块
            spirit.setAttribute("style", `top:${startY-25}px;left:${startX-25}px`)

            // 追加到当前画布中
            canvase.appendChild(spirit)

        }

        function touchMove(event) {
            event.preventDefault();
            if (!spirit || !event.touches.length) return;
            var touch = event.touches[0]
            startX = touch.clientX
            startY = touch.clientY
            spirit.setAttribute("style", `top:${startY-25}px;left:${startX-25}px`)
        }


        function touchEnd(event) {
            if (!spirit) return;
            spirit.remove()
            spirit = null
        }
        canvase.addEventListener("touchstart", touchStart, false)
        canvase.addEventListener("touchmove", touchMove, false)
        canvase.addEventListener("touchend", touchEnd, false)
    </script>

</body>

</html>